<template>
  <div class="box">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="roleList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row 
                  :class="['bottom', index1 === 0 ? 'top' : '']" 
                  class="v-center"
                  v-for="(item1, index1) in scope.row.children" :key="item1.id" >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable
                        @close="removeRightsByTd(scope.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染 二级 三级 权限 -->
              <el-col :span="19">
                <!-- 通过 for 循环嵌套渲染二级权限 -->
                <el-row 
                      :class="[index2 === 0 ? '' : 'top']"
                      class="v-center"
                      v-for="(item2, index2) in item1.children" :key="item2.id">
                  <!-- 渲染 二级 权限 -->
                  <el-col :span="6">
                    <el-tag type="success" 
                            closable
                            @close="removeRightsByTd(scope.row, item2.id)">
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染 三级 权限 -->
                  <el-col :span="18">
                    <el-tag v-for="item3 in item2.children" :key="item3.id"
                            type="warning"
                            closable
                            @close="removeRightsByTd(scope.row, item3.id)">
                      {{ item3.authName }}
                    </el-tag>
                    
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#" />
        <el-table-column label="角色名称" prop="roleName" />
        <el-table-column label="角色描述" prop="roleDesc" />
        <el-table-column label="操作" width="300px">
          <!-- 作用域插槽会覆盖掉 prop -->
          <!-- scope 接收作用域差槽的数据 -->
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button 
                  type="warning" 
                  icon="el-icon-setting" 
                  size="mini"
                  @click="showSetRightsDialog(scope.row)">
              分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 展示分配权限的对话框 -->
    <el-dialog 
          title="分配权限" 
          :visible.sync="setRightsDialogVisible"
          width="50%"
          :modal="false"
          @close="setRightsDialogClose">
      <!-- 树形控件，显示树结构 -->
      <el-tree 
            :data="rightsList" 
            :props="rightsProps" 
            show-checkbox 
            node-key="id"
            default-expand-all
            :default-checked-keys="defKeys"
            ref="treeRef">
      </el-tree>
      <span slot="footer">
        <el-button @click="setRightsDialogVisible = false">取消</el-button>
        <el-button 
              type="primary" 
              @click="allotRights">
          确定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'RightsList',
  data() {
    return {
      // 所有角色列表数据
      roleList: [],
      // 控制分配权限对话框的显示与隐藏
      setRightsDialogVisible: false,
      // 所有权限数据
      rightsList: [],
      // 树形控件的属性绑定对象
      rightsProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点 id值 数组
      defKeys: [],
      // 当前即将分配权限的角色 id
      roleId: '',
    }
  },
  methods: {
    // 获取角色列表数据
    async getRoleList() {
      const {data: res} = await this.axios.get('data/roles.json');
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表数据失败')
      }
      this.roleList = res.data
      this.$message.success('获取角色列表数据成功')
      console.log(this.roleList);
    },

    // 根据 id 删除对应的权限
    async removeRightsByTd(role, rightsId) {
      // 弹框提示用户是否删除
      const confirmResult = await this.$confirm('确定删除权限？','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // 如果用户取消了删除：
      if (confirmResult !== 'confirm') {
        return this.$message.info('以取消删除');
      }

      // 如果用户确定删除
      const { data: res } = this.axios.delete(`roles/${role.id}/rights/${rightsId}`);

      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }

      role.children = res.data
    },

    // 展示分配权限的对话框
    async showSetRightsDialog(role) {
      this.roleId = role.id
      console.log('即将分配权限的角色 id:', this.roleId);
      // 获取所有权限数据 (rights/tree) tree 表示 获取类型
      const { data: res } = await this.axios.get('data/rightslist.json');
      if (res.meta.status !== 200) {
        return this.$message.error('获取所有权限数据失败')
      }

      // 获取到的权限数据保存到 data 中
      this.rightsList = res.data
      // console.log(this.rightsList);

      // 递归获取三级节点的 id
      this.getLeafKeys(role, this.defKeys);

      this.setRightsDialogVisible = true
      // console.log(this.defKeys);
    },
    // 监听对话框的关闭
    setRightsDialogClose() {
      this.defKeys = [];
    },

    // 通过递归的形式，获取角色下所有三级权限的id， 并保存到 defKeys 数组中
    getLeafKeys(node, arr) {
      // 如果当前节点 不包含 children ，则是三级节点， 保存它的 id
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => this.getLeafKeys(item, arr));
    },

    // 给角色分配权限 
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      // console.log(keys);
      const idStr = keys.join(',')
      const { data: res } = await this.axios.post(`roles/${this.roleId}/rights`, { rids: idStr });

      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRoleList();
      this.setRightsDialogVisible = false
    },
  },
  created() {
    this.getRoleList();
  }
}
</script>

<style lang="less" scoped>
  .box {
    width: 80%;
    overflow-y: scroll;
  } 
  .el-card {
    margin-top: 20px;
  }
  .el-tag {
    margin: 10px;
  }
  .top {
    border-top: 1px solid #eee;
  }
  .bottom {
    border-bottom: 1px solid #eee;
  }
  .v-center {
    display: flex;
    align-items: center;
  }
</style>